<template>
  <div class="detail">
    <div class="detail-head">
      <van-nav-bar
        title="商品详情"
        left-text="返回"
        @click-left="back"
        left-arrow
        :fixed="true"
      />
      <div class="detail-img">
        <img class="auto-img" :src="dataildata.large_img" alt />
        <div class="detail-name">
          <div>{{ dataildata.name }}</div>
          <div class="eng">{{ dataildata.enname }}</div>
        </div>
      </div>
    </div>
    <div class="detail-body">
      <div class="specification">
        <div
          class="specifications"
          v-for="(value, index) in dataildata.rules"
          :key="index"
        >
          <div class="rules-title">{{ value.title }}</div>
          <div
            class="rules-rulestitle"
            v-for="(v, i) in value.rules"
            :key="i"
            :class="{ active: v.isActive }"
            @click="toggbg(v, index)"
          >
            <span>{{ v.title }}</span>
          </div>
        </div>
      </div>

      <div class="introduce">
        <div class="describe">商品描述</div>
        <div
          class="introduces"
          v-for="(value, index) in dataildata.desc"
          :key="index"
        >
          {{ index }}.{{ value }}
        </div>
      </div>

      <div class="price">
        <div class="prices">￥{{ numprice }}</div>
        <div class="count">
          <van-stepper
            v-model="count"
            theme="round"
            button-size="24"
            disable-input
          />
        </div>
      </div>
    </div>
    <div class="detail-bottom">
      <van-goods-action>
        <van-goods-action-icon
          icon="cart"
          text="购物车"
          :badge="number"
          @click="goshop"
        />
        <van-goods-action-icon
          icon="star"
          :color="isLike ? '#0C34BA' : '#999'"
          text="收藏"
          @click="shoucang"
        />
        <van-goods-action-button
          type="warning"
          text="加入购物车"
          @click="addshop(1)"
        />
        <van-goods-action-button
          type="danger"
          text="立即购买"
          @click="addshop(-1)"
        />
      </van-goods-action>
    </div>
  </div>
</template>

<script>
import '../assets/less/detail.less'
import {
  detailAPI,
  isLikeAPI,
  findlikeAPI,
  findAllShopcartAPI,
  addShopcartAPI
} from '@/api/user'
import { getToken } from '@/utils/storage'

export default {
  data () {
    return {
      pid: '',
      dataildata: {},
      count: 1,
      isLike: false,
      number: 0
    }
  },
  computed: {
    numprice () {
      // return 0
      return this.count * this.dataildata.price
    }
  },
  created () {
    // 进来先获取传过来的pid
    this.pid = this.$route.query.pid
    this.loading()
    this.islike()
    this.eachshop()
  },
  methods: {
    // 去购物车
    goshop () {
      this.$router.push({ name: 'Shop' })
    },
    // 返回上一级
    back () {
      this.$router.go(-1)
    },
    // 加载商品详情数据
    async loading () {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0,
        loadingType: 'spinner'
      })
      const res = await detailAPI({
        pid: this.pid,
        appkey: this.$store.state.appkey
      })
      if (res) {
        this.$toast.clear()
        if (res.code === 600) {
          // 将描述进行分割
          res.result[0].desc = res.result[0].desc.split(/\n/)
          // 给规格分组 温度 甜度  牛奶 奶油
          const specification = ['tem', 'sugar', 'milk', 'cream']
          const specificationData = []
          specification.forEach(v => {
            // 查询返回数据中是否有规格，如果有则添加，无则跳过
            if (res.result[0][v] === '') {
              return
            }
            // 规格1级分组
            const rule = {
              title: res.result[0][v + '_desc'],
              rules: []
            }
            // 规格2级分组
            const r = res.result[0][v].split('/')
            r.forEach((value, index) => {
              const o = {
                title: value,
                isActive: index === 0
              }
              rule.rules.push(o)
            })
            specificationData.push(rule)
          })
          // 将规格分类好后保存
          res.result[0].rules = specificationData
          this.dataildata = res.result[0]
        }
      } else {
        this.$toast.clear()
      }
    },
    // 监测是否收藏
    async islike () {
      const tokenString = getToken()
      if (!tokenString) return
      const res = await findlikeAPI({
        pid: this.pid,
        appkey: this.$store.state.appkey,
        tokenString
      })
      if (res.code === 1000 && res.result.length === 1) {
        this.isLike = true
      }
    },
    // 选择商品规格
    toggbg (v, index) {
      if (v.isActive) {
        return
      }
      // 选中的规格高亮，其他取消高亮
      for (let i = 0; i < this.dataildata.rules[index].rules.length; i++) {
        this.dataildata.rules[index].rules[i].isActive = false
      }
      v.isActive = !v.isActive
    },
    // 收藏、取消收藏商品
    async shoucang () {
      const url = !this.isLike ? '/like' : '/notlike'
      const tokenString = getToken()
      if (!tokenString) return this.$router.push({ name: 'Login' })
      const res = await isLikeAPI(url, {
        pid: this.pid,
        appkey: this.$store.state.appkey,
        tokenString
      })
      // 如果用户没登录则跳转到登录页面
      if (res.code === 700) {
        return this.$router.push({ name: 'Login' })
      }
      // 收藏
      if (res.code === 800) {
        this.$toast('收藏成功')
        this.isLike = true
      }
      // 取消收藏
      if (res.code === 900) {
        this.isLike = false
        this.$toast('取消收藏')
      }
    },
    // 加入购物车-立即购买
    async addshop (num) {
      const tokenString = getToken()
      if (!tokenString) return this.$router.push({ name: 'Login' })
      // 获取选择的规格
      const rules = this.dataildata.rules
      const rule = []
      rules.forEach(v => {
        for (let i = 0; i < v.rules.length; i++) {
          if (v.rules[i].isActive) {
            rule.push(v.rules[i].title)
            break
          }
        }
      })
      const data = {
        appkey: this.$store.state.appkey,
        pid: this.pid,
        tokenString,
        count: this.count,
        rule: rule.join('/')
      }
      const res = await addShopcartAPI(data)
      if (res.code === 3000) {
        // 如果是立即购买则加购后跳转到提交
        if (num === -1) {
          const sid = []
          sid.push(res.sid)
          const obj = JSON.stringify(sid)
          this.$router.push({ name: 'Tijiao', query: { obj } })
          return
        }
        this.$toast(res.msg)
        if (res.status === 1) {
          // 累加徽章数量, 购物车数据，而不是购物车商品总数量
          this.number++
        }
      }
    },
    // 查询购物车数量
    async eachshop () {
      const tokenString = getToken()
      if (!tokenString) return
      const res = await findAllShopcartAPI({
        appkey: this.$store.state.appkey,
        tokenString
      })
      if (res.code === 5000) {
        this.number = res.result.length
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
